<template lang="html">
  <div class="content-container book-chapter-container">
    <!--筛选条件项-->
    <div class="content-condition filter searchBox" id="filterId">
      <div class="filterBtn">
        <el-button type='primary' @click="searchFun" :icon="Search">搜索</el-button>
        <el-button type="danger" @click="resetSearchData" :icon="RefreshRight">重置</el-button>
      </div>

      <el-select v-model="searchData.bookId" filterable style="width: 150px" placeholder="书籍" clearable>
        <el-option v-for="item in options.bookSelector" :key="item.value" :label="item.label"
          :value="item.value"></el-option>
      </el-select>

      <el-input v-model="searchData.chapterName" :clearable="true" placeholder="章节名称" style="width: 180px"> </el-input>

      <el-select v-model="searchData.crawlComplete" filterable style="width: 150px" placeholder="爬取状态" clearable>
        <el-option v-for="item in options.crawlCompleteSelector" :key="item.value" :label="item.label"
          :value="item.value"></el-option>
      </el-select>

      <el-select v-model="searchData.matchSource" filterable style="width: 150px" placeholder="匹配状态" clearable>
        <el-option v-for="item in options.matchSourceSelector" :key="item.value" :label="item.label"
          :value="item.value"></el-option>
      </el-select>
    </div>

    <el-row class="special content-condition buttonBox" id="buttonId">
      <el-col :span="24" ref="limitBtnWidth">
        <el-space :size="10" id="actualBtnWidth" class="actualBtnWidth">
          <el-button type="success" @click="editFun" :icon="Edit">编辑</el-button>
          <el-button type="danger" @click="deleteFun" :icon="Delete">删除</el-button>
          <el-button type="danger" @click="syncContentFun" :icon="RefreshRight">同步正文</el-button>
        </el-space>
      </el-col>
    </el-row>

    <!--表格-->
    <div class="table content-condition">
      <common-table :isShowLoading="tableData.poolIsShowLoading" :tableId="tableData.tableId"
        :columns="tableData.columns" emptyText="没有找到数据" :data="tableData.datas" :tableType="tableData.tableType"
        :pager="tableData.pager" @handleCurrentChange="handleCurrentChange" @handleSizeChange="handleSizeChange"
        @handleSelectionChange="handleSelectionChange" @handleExpandChange="handleExpandChange" :rowkey="'id'"
        :expandRowKeys="tableData.expandRowKeys" ref="table">
        <template v-slot:table_checkbox>
          <el-table-column type="selection" align="center" width="55" fixed="left"></el-table-column>
        </template>
        <template #catalogueNameSlot="slotData">
          <div class="chapterName" @click="openContentLink(slotData.scope.row)">{{ slotData.scope.row.catalogueName }}
          </div>
        </template>

        <template #operationSlot="slotData">
          <Button :chapter="slotData.scope.row" :book-id="searchData.bookId"></Button>
        </template>
      </common-table>
    </div>
  </div>
  <Detail ref="chapterDetailDialog"></Detail>
</template>
<script setup lang="js">
import { onMounted, ref, inject, provide, defineExpose } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Edit, Delete, Search, RefreshRight } from '@element-plus/icons-vue';
import _ from 'lodash';

import { getBookSelectItems } from '@/api/book';
import { deleteChapter, getPageList } from '@/api/chapterMgr';
import Detail from './components/Detail.vue';
import Button from './components/Button.vue';
const { createTask, taskCodes } = inject('taskProvide');

const initSearchData = () => {
  return {
    bookId: '',
    chapterName: '',
    crawlComplete: null, // 爬取状态
    matchSource: null, // 匹配状态
    pageIndex: 0,
    pageSize: 20,
  };
};

const props = defineProps({
  bookId: {
    type: String,
    default: ''
  }
});

const chapterDetailDialog = ref(null); // 章节详情弹窗
const searchData = ref(initSearchData());
const options = ref({
  bookSelector: [],
  crawlCompleteSelector: [
    { value: null, label: '全部' },
    { value: true, label: '已完成' },
    { value: false, label: '未完成' }
  ],
  matchSourceSelector: [
    { value: null, label: '全部' },
    { value: true, label: '已匹配' },
    { value: false, label: '未匹配' }
  ]
});

const tableData = ref({
  tableId: 'chapterTable',
  tableType: ["table"], //table-表格 dualCard-双卡片 其它-单卡片
  columns: [
    {
      prop: "volumeName",
      label: "卷",
      width: "50",
      align: "left",
      sortable: false,
      show: true
    },
    {
      slotName: "catalogueNameSlot",
      label: "章节名称",
      width: "80",
      align: "left",
      sortable: false,
      show: true
    },
    {
      prop: "keyword",
      label: "关键字",
      width: "80",
      align: "left",
      sortable: false,
      show: true
    },
    {
      prop: "wordsNumber",
      label: "字数",
      width: "50",
      align: "left",
      sortable: false,
      show: true
    },
    {
      prop: "crawlComplete",
      label: "爬取状态",
      width: "40",
      align: "left",
      sortable: false,
      formatter: function (row) {
        return row.crawlComplete ? '已完成' : '未完成';
      },
      show: true
    },
    {
      prop: "isMatchSource",
      label: "是否匹配源",
      width: "40",
      align: "left",
      sortable: false,
      formatter: function (row) {
        return row.isMatchSourceDesc
      },
      show: true
    },
    {
      prop: "createDateTime",
      label: "创建时间",
      width: "60",
      align: "left",
      sortable: false,
      show: false
    },
    {
      prop: "updateDateTime",
      label: "更新时间",
      width: "60",
      align: "left",
      sortable: false,
      show: false
    },
    {
      slotName: "operationSlot",
      label: "操作",
      width: "100",
      align: "left",
      sortable: false,
      show: true
    },
  ],
  datas: [],
  pager: {
    //分页栏信息
    pageNo: 1, //第几页
    limit: 20, //每页记录数
    sizes: [10, 20, 50, 200, 500, 1000],
    total: 0, //总记录数
    isShow: true //是否显示
  },
  expandRowKeys: [],
  selectedRows: [],
  poolIsShowLoading: false,
}, {
  deep: true,
});

// Methods
/**
 * 搜索
 * @param isFirstPage 是否是第一页
 */
function searchFun(isFirstPage = true) {
  // 这里可以添加搜索逻辑
  if (!searchData.value.bookId) {
    ElMessage.error("请选择书籍进行搜索");
    return false;
  }
  if (isFirstPage) {
    searchData.value.pageIndex = 0; // 重置页码为第一页
  }
  console.log('搜索条件:', searchData.value);
  tableData.value.poolIsShowLoading = true;
  getDataFun();
}

/**
 * 重置
 */
function resetSearchData() {
  Object.assign(searchData.value, initSearchData());
}

/**
 * 获取数据
 */
const getDataFun = _.debounce(() => {
  let params = Object.assign({}, searchData.value);
  getPageList(params).then((res) => {
    tableData.value.datas = res.data.data;
    tableData.value.pager = Object.assign({}, tableData.value.pager, {
      total: res.data.records,
      limit: res.data.pageSize,
      pageNo: res.data.pageIndex + 1
    });
  }).finally(() => {
    tableData.value.poolIsShowLoading = false;
  });
}, 300);

/**
 * 改变页码
 * @param pageNo 当前页码
 */
function handleCurrentChange(pageNo) {
  searchData.value.pageIndex = pageNo;
  searchFun(false);
}

/**
 * 改变每页记录数
 * @param pageSize 每页记录数
 */
function handleSizeChange(pageSize) {
  searchData.value.pageSize = pageSize;
  searchFun();
}

/**
 * 处理选中行变化
 * @param selection 选中行数据
 */
function handleSelectionChange(selection) {
  tableData.value.selectedRows = selection;
}

function editFun() {
  if (tableData.value.selectedRows.length !== 1) {
    ElMessage.warning("请选择一条记录进行编辑");
    return;
  }
  chapterDetailDialog.value.openDialog(tableData.value.selectedRows[0]);
}

function deleteFun() {
  if (tableData.value.selectedRows.length === 0) {
    ElMessage.warning("请选择任意一条记录进行删除");
    return;
  }

  const ids = tableData.value.selectedRows.map(item => item.id);
  ElMessageBox.confirm('此操作将永久删除选中的书籍, 是否继续?',
    '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    tableData.value.poolIsShowLoading = true;
    deleteChapter(ids.join(',')).then((res) => {
      if (res == null || !res.isSuccess) {
        ElMessage.error(res.message || "操作失败");
        return;
      }
      ElMessage.success("删除成功");
      searchFun();
    }).finally(() => {
      tableData.value.poolIsShowLoading = false;
    });
  }).catch(() => {
    ElMessage.info("已取消删除操作");
  });
}
function syncContentFun() {
  if (tableData.value.selectedRows.length === 0) {
    ElMessage.warning("请选择任意一条记录进行同步正文");
    return;
  }

  const ids = tableData.value.selectedRows.map(item => item.id);
  createTask({
    taskCode: taskCodes.syncManualCrawlContent,
    parameters: {
      filter: {
        bookId: searchData.value.bookId,
        chapterId: ids.join(','),
      }
    },
  })
}

function openContentLink(chapter) {
  window.open(chapter.contentLink, '_blank');
}

function setBookId(bookId) {
  resetSearchData();
  searchData.value.bookId = bookId;
  searchFun();
}

/**
 * 初始化选项数据
 */
function initOptions() {
  getBookSelectItems().then((response) => {
    options.value.bookSelector = response.data;
    if (!searchData.value.bookId) {
      searchData.value.bookId = options.value.bookSelector.length > 0 ? options.value.bookSelector[0].value : '';
      searchFun();
    }
  }).catch((error) => {
    ElMessage.error('获取书籍列表失败');
  });
}

onMounted(() => {
  initOptions();
});

provide('chapterMgrProvide', {
  onSuccess: searchFun,
})

defineExpose({
  setBookId: setBookId,
});

</script>
<style lang="less">
.book-chapter-container {
  .chapterName {
    cursor: pointer;
    text-decoration: underline;
  }
}
</style>
